
import hashlib

from pony.orm import db_session, select, OrmError

from base.core import BaseTornadoHandler
from db.model import AuthToken, User
from utils.loger import run_log
from utils.response import ApiResponse
import functools


class ApiLogin(BaseTornadoHandler):

    @staticmethod
    def required(method):
        @functools.wraps(method)
        def wrapper(self, *args, **kwargs):
            if not self.current_user:
                self.write(ApiResponse.fail(-1, msg="login required"))
                return
            return method(self, *args, **kwargs)
        return wrapper

    @db_session
    def post(self):
        data = self.try_get_json()
        account = data.get("account", "")
        password = data.get("pwd", "")
        if not account or not password:
            self.write(ApiResponse.fail(-1, msg="mobile or pwd can not be empty"))
            return
        user = select(u for u in User if u.account == account).first()
        if not user:
            self.write(ApiResponse.fail(-1, msg="not registered"))
            return
        if user.is_pwd_right(password):
            data = {
                "auth_token": AuthToken.gen_token_for_user(user)
            }
            self.write(ApiResponse.success(data))
            return
        else:
            self.write(ApiResponse.fail(-1, msg="password error"))
            return


class ApiRegister(BaseTornadoHandler):

    @db_session
    def post(self):
        data = self.try_get_json()
        account = data.get("account", "")
        pwd = data.get("pwd", "")
        repeat_pwd = data.get("repeat_pwd", "")
        if not all((account, pwd, repeat_pwd)):
            self.write(ApiResponse.fail(-1, msg="miss params"))
            return
        if pwd != repeat_pwd:
            self.write(ApiResponse.fail(-1, msg="password validate failed"))
            return

        m = hashlib.md5()
        m.update(pwd.encode("utf-8"))
        try:
            User.create_base_user(account=account, password=m.hexdigest())
        except OrmError as e:
            run_log.error(e)
            self.write(ApiResponse.fail(-1, msg="unknown error"))
            return

        self.write(ApiResponse.success())


class ApiLogout(BaseTornadoHandler):

    @db_session
    def delete(self):
        if self.current_user:
            token = self.current_user.token
            token.delete()
        self.write(ApiResponse.success())
